package com.bjpowernode.web.controller;

import com.bjpowernode.common.P2PConstants;
import com.bjpowernode.model.User;
import com.bjpowernode.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
public class RechargeController {

    @Value("${pay.alipay.url}")
    private String alipayUrl;

    //充值页面
    @GetMapping("/loan/page/toRecharge")
    public String toRechargePage() {

        return "toRecharge";
    }

    @PostMapping("/loan/recharge/alipay")
    @ResponseBody
    public void toAlipay(@RequestParam("rechargeMoney") BigDecimal money, HttpSession session, HttpServletRequest request,HttpServletResponse response) {
        System.out.println("==========toAlipay");

        //使用HttpClient向p2p-pay发送一个请求，获取一个String result="<form></form>"
        User user = (User) session.getAttribute(P2PConstants.SESSION_USER);
        Map<String, Object> param = new HashMap<>();
        param.put("uid", user.getId());
        param.put("money", money.toString());
        param.put("channel", "alipay");
        try {
            String form = HttpClientUtils.doPost(alipayUrl,param);
            System.out.println("接收pay应用返回的string="+form);

            if ("error".equals(form)){
                response.sendRedirect(request.getContextPath()+"/loan/error");
            }else {
                PrintWriter writer = response.getWriter();
                writer.println(form);
                writer.flush();
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
